package com.dhnsoft.每天一道力扣;

import java.util.Arrays;

public class day03_977_有序数组的平方 {

    public static void main(String[] args) {
        int[] nums = {-7,-3,2,3,11};
//        int[] ints = sortedSquares(nums);
        int[] ints = sortedSquares2(nums);
//        System.out.println(Arrays.toString(ints));
    }


    public static int[] sortedSquares(int[] nums) {
        for (int i = 0; i < nums.length; i++) {
            nums[i] = (int) Math.pow(nums[i],2);
        }
        for (int i = 0; i < nums.length; i++) {
            for (int j = 0; j < nums.length - 1; j++) {
                if(nums[j]>nums[j+1]){
                    int temp = nums[j+1];
                    nums[j+1] = nums[j];
                    nums[j]=temp;
                }
            }
        }

        return nums;
    }

    public static int[] sortedSquares2(int[] nums) {
        int[] nums_2 = new int[nums.length];
        int k = nums.length-1;
        for (int i=0,j=nums.length-1;i<=j;){
            if((int) Math.pow(nums[i],2)>=(int) Math.pow(nums[j],2)){
                nums_2[k--] = (int) Math.pow(nums[i],2);
                i++;
            }
            else{
                nums_2[k--] = (int) Math.pow(nums[j],2);
                j--;
            }
        }
        System.out.println(Arrays.toString(nums_2));
        return nums_2;
    }
}
